package com.zheng.redpacket.server.controller.redisson;

import com.zheng.redpacket.api.CommonResult;
import com.zheng.redpacket.api.RequestErrorCode;
import com.zheng.redpacket.api.ResultCode;
import com.zheng.redpacket.mdg.model.Praise;
import com.zheng.redpacket.server.dto.PraiseDto;
import com.zheng.redpacket.server.serivce.PraiseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/blog/praise")
public class PraiseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(PraiseController.class);

    @Autowired
    PraiseService praiseService;

    @PostMapping("/add")
    public CommonResult addPraise(@RequestBody PraiseDto dto) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            praiseService.addPraise(dto);
            Long total = praiseService.getBlogPraiseTotal(dto.getBlogId());
            resultMap.put("praiseTotal", total);
        } catch (Exception e) {
            LOGGER.error("点赞博客，发生异常{}", dto, e.fillInStackTrace());
            CommonResult.failed(ResultCode.FAILED, e.getMessage());
        }
        return CommonResult.success(resultMap);
    }

    @PostMapping("/cancel")
    public CommonResult cancelPraise(@RequestBody PraiseDto dto) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            praiseService.cancelPraise(dto);
            Long total = praiseService.getBlogPraiseTotal(dto.getBlogId());
            resultMap.put("praiseTotal", total);
        } catch (Exception e) {
            LOGGER.error("点赞博客，发生异常{}", dto, e.fillInStackTrace());
            CommonResult.failed(ResultCode.FAILED, e.getMessage());
        }
        return CommonResult.success(resultMap);
    }

    @GetMapping("/rank")
    public CommonResult rankPraise() {
        try {
            return CommonResult.success(praiseService.getRank());
        } catch (Exception e) {
            LOGGER.error("排行榜功能异常", e.fillInStackTrace());
            return CommonResult.failed(ResultCode.FAILED, e.getMessage());
        }
    }

}
